﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using AchieveManageWeb.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    public class CostAccountController : Controller
    {
        //
        // GET: /CostAccount/

        public ActionResult Index()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "成本核算")); //日志记录
          return View();
        }
        /// <summary>
        /// 成本核算查询控制器
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCostAccountEntry()
        {
            //前端查询参数:项目编号：ProjectNo,物料名称：ItemName,规格型号：ItemModel
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ItemName = Request["ItemName"] == null ? "" : Request["ItemName"];
            string ItemModel = Request["ItemModel"] == null ? "" : Request["ItemModel"];
            string sql=string.Empty;
            string content = "";
            string strWhere = "1=1"; 
            string sort = Request["sort"] == null ? "ProjectID" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量
            //按项目编号查询
            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))   //防止sql注入
            { 
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());  
                    int totalCount;   //输出参数 
                    //DataTable dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark,status,Department,IcmoNo,FitemNo,FName,FModel", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                    DataTable dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,IcmoNo,FitemNo,FName,FModel", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
  
                    //获取当前用户的角色及其能查看的成本项目；
                    UserEntity uInfo = ViewData["Account"] as UserEntity;
                    DataTable dt_user_role = new RoleBLL().GetRoleByUserId(uInfo.ID);  //用户之前拥有的角色
                    string roles = AchieveCommon.JsonHelper.ColumnToJson(dt_user_role, 0);
                    //角色-字段；
                    string sqlfields = "select distinct fieldName from tbRoleField where pageName='PMIndex' and roleId in (" + roles + ")";
                    DataTable fields = SqlHelper.GetDataTable(SqlHelper.connStr, sqlfields);
                    foreach (DataRow item in fields.Rows)
                    {
                        dt.Columns.Add(item[0].ToString());//添加成本字段；
                        //判断是否输出实际成本，如需要则实时计算；
                        if (item[0].ToString() == "reaCost")
                        {         //实时查询计算实际成本；
                            foreach (DataRow dtItem in dt.Rows)
                            {
                                dtItem["reaCost"] = AchieveBLL.CostBLL.realCostCal(dtItem["ProjectNo"].ToString());
                            }
                        }
                    }

                    //添加附加表信息
                    foreach (DataRow item in dt.Rows)
                    { 
                        string sql2 = string.Format("select estCost,budCost,stdCost,plaCost from tbProjectCost where projectid='{0}'", item["ProjectID"].ToString());
                        DataTable dtcosts = SqlHelper.GetDataTable(SqlHelper.connStr, sql2);
                        //添加相应的成本字段值
                        if (dtcosts.Rows.Count == 1)
                        {
                            foreach (DataRow item2 in fields.Rows)
                            {
                                if (item2[0].ToString() != "reaCost") { 
                                item[item2[0].ToString()] = dtcosts.Rows[0][item2[0].ToString()];
                                }                                
                            }
                        }

                    string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
                    return Content(content);
                }
            }

            //按物料查询
            if (ItemName.Trim() != "" && !SqlInjection.GetString(ItemName) || (ItemModel.Trim() != "" && !SqlInjection.GetString(ItemModel)))   //防止sql注入
            { 
              sort = Request["sort"] == null ? "FName" : Request["sort"];
              order = Request["order"] == null ? "desc" : Request["order"]; 
            //首先获取前台传递过来的参数
              string FName = Request["ItemName"] == null ? "" : Request["ItemName"];
              string FModel = Request["ItemModel"] == null ? "" : Request["ItemModel"];
 
            if (FName !="")
            {
                strWhere += string.Format(" and b.FName like '%{0}%'",FName);
            }
            if (FModel!="")
            {
                 strWhere += string.Format(" and b.FModel like '%{0}%'",FModel);
            } 
            int totalCount;
            string tablename = "icbom a left join t_ICITEMCORE b on a.FItemID=b.FItemID left join t_icitemdesign c on  a.FItemID=c.FItemID left join t_ICItemStandard d on a.FItemID=d.FItemID";
            string innercolumns = "a.FInterID as bomID,a.FItemID,a.FHEADSELFZ0132 as itemPrice,b.FName,b.FModel,b.FNumber,b.FOrderPrice,c.fnetweight,c.FGrossWeight,d.FstandardCost,d.FstandardManHour";
            string outcolumns = "bomID,FItemID,FName,FModel,FNumber as FitemNo,itemPrice,fnetweight,FOrderPrice,FGrossWeight,FstandardCost,FstandardManHour";
            string sort1 = "a.FInterID desc";
            DataTable dt = SqlHelper.GetPagerDataTable(tablename, innercolumns, outcolumns, pageindex, pagesize, strWhere, sort1, out totalCount, true);
            
                //计算并添加标准成本
            dt.Columns.Add("stdCost",typeof(decimal));
            foreach (DataRow row in dt.Rows)
            {
                decimal FstandardCost = 0;
                decimal FstandardManHour = 0;

                if ( !row["FstandardCost"].Equals(DBNull.Value)){
                      FstandardCost = Convert.ToDecimal(row["FstandardCost"]);
                }
                if ( !row["FstandardManHour"].Equals(DBNull.Value))
                    {
                        FstandardManHour = Convert.ToDecimal(row["FstandardManHour"]);
                    }

                    if (FstandardCost > 0)
                    {
                        row["stdCost"] = FstandardCost + FstandardManHour * 20;
                            } else {
                                row["stdCost"] =  row["ForderPrice"];
                            }
            }
                
                string strJson = JsonHelper.ToJson(dt);
            content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            return Content(content); 
            } 
            
            content = "{\"total\":0 ,\"rows\":[] }";
            return Content(content);

            //return Content(easyUiHelper.queryDatagridJson(sql, true));
        }
        
    }
}
